/**
 * 
 */
package com.miolr.core.dao.hibernate;

import java.io.Serializable;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang3.ArrayUtils;
import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;

import com.miolr.core.model.Auditable;

/**
 * @author iday
 *
 */
public class GeneratedDateInterceptor extends EmptyInterceptor {

	/**
	 * 
	 */
	private static final long serialVersionUID = -9177675372214038112L;

	/* (non-Javadoc)
	 * @see org.hibernate.EmptyInterceptor#onFlushDirty(java.lang.Object, java.io.Serializable, java.lang.Object[], java.lang.Object[], java.lang.String[], org.hibernate.type.Type[])
	 */
	@Override
	public boolean onFlushDirty(Object entity, Serializable id,
			Object[] currentState, Object[] previousState,
			String[] propertyNames, Type[] types) {
		if (entity instanceof Auditable<?, ?>) {
			Date date = Calendar.getInstance().getTime();
			int i = ArrayUtils.indexOf(propertyNames, "lastModified");
			currentState[i] = date;
			return true;
		}
		return false;
	}

	/* (non-Javadoc)
	 * @see org.hibernate.EmptyInterceptor#onSave(java.lang.Object, java.io.Serializable, java.lang.Object[], java.lang.String[], org.hibernate.type.Type[])
	 */
	@Override
	public boolean onSave(Object entity, Serializable id, Object[] state,
			String[] propertyNames, Type[] types) {
		if (entity instanceof Auditable<?, ?>) {
			Date date = Calendar.getInstance().getTime();
			int i = ArrayUtils.indexOf(propertyNames, "created");
			state[i] = date;
			int j = ArrayUtils.indexOf(propertyNames, "lastModified");
			state[j] = date;
			return true;
		}
		return false;
	}

}
